package com.hundredapp.oa.dao;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
/**
 * 
 * @author 
 *
 * @param <T>
 * @param <ID>
 */

public class GenericDaoImpl<T, ID extends Serializable> implements GenericDao<T, ID> {
	// 具体的实体类型
	private Class<T> type;
	public GenericDaoImpl(Class<T> clazz){
		type=clazz;
	}
	
	@Autowired
	private HibernateTemplate hibernateTemplate;
	
	@Autowired
	private SessionFactory sessionFactory;
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
    
	public T findById(ID id) {
		return (T) hibernateTemplate.get(type, id);
	}
	public void modify(T entity) {
		hibernateTemplate.update(entity);
	}
	public void remove(T entity) {
		hibernateTemplate.delete(entity);
	}
	
	public void removeAll(Collection<T> entities) {
		hibernateTemplate.deleteAll(entities);		
	}
	
	@SuppressWarnings("unchecked")
	public ID save(T entity) {
		return (ID) hibernateTemplate.save(entity);
	}
	
	@SuppressWarnings("unchecked")
	public void saveOrUpdate(T entity) {
		hibernateTemplate.saveOrUpdate(entity);
	}

	@SuppressWarnings("unchecked")
	public List<T> find(String condition) {
		String hql = "from " + type.getName();
		if(!condition.isEmpty()){
			hql+=" where "+condition;
		}
		return hibernateTemplate.find(hql);
	}

	@SuppressWarnings("unchecked")
	public T findUnique(String condition) {
		String hql = "from " + type.getName();
		if(!condition.isEmpty()){
			hql+=" where "+condition;
		}
		List<T> result=hibernateTemplate.find(hql);
		if(!result.isEmpty()){
			return result.get(0);
		}
		
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public List<T> find(String condition,int start,int limit){
		String hql = "from " + type.getName();
		if(!condition.isEmpty()){
			hql+=" where "+condition;
		}
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setMaxResults(limit);
		query.setFirstResult(start);
		return query.list();
	}
	
	public int count(String condition){
		String hql = "select count(*) from " + type.getName();
		if(!condition.isEmpty()){
			hql+=" where "+condition;
		}
		return ((Long) sessionFactory.getCurrentSession().createQuery(hql).uniqueResult()).intValue();
	}
	
	@SuppressWarnings("unchecked")
	public List<T> executeQuery(String hql, Object...values) {
		return hibernateTemplate.find(hql, values);
	}
}

